<template>
  <div>
    <div v-if="crud.props.searchToggle">
      <el-input
        type="text"
        placeholder="输入名称搜索"
        style="width: 200px;"
        size="small"
        class="filter-item"
        v-model="query.name"
      />
      <rrOperation :crud="crud" />
    </div>
    <crudOperation :permission="permission">
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-folder-add"
        @click="newFolder"
      >新建文件夹</el-button>
      <el-upload
        slot="right"
        class="filter-item f-upload"
        action=""
        :http-request="uploadFile"
        :show-file-list="false">
        <el-button size="mini" icon="el-icon-upload2" type="primary">上传</el-button>
      </el-upload>
    </crudOperation>

    <el-row>
      <template v-if="suffixFolder===''">
        <el-button type="text"><el-link type="info" :underline="false">全部文件</el-link></el-button>
      </template>
      <template v-else>
        <el-button type="text" @click="goBack">返回上一级</el-button>
        <el-button type="text">|</el-button>
        <el-button type="text" @click="goBackFirst">全部文件</el-button>
      </template>
    </el-row>
    <el-table ref="table" size="small" :row-class-name="tableRowClassName" v-loading="crud.loading" row-key="index" :data="crud.data" :default-sort="{prop: 'directory', order: 'descending'}"  @select="crud.selectChange" @select-all="crud.selectAllChange" @selection-change="crud.selectionChangeHandler" @row-click="rowClick" @row-contextmenu="rowContextmenu" @cell-mouse-enter="cellMouseEnter" @cell-mouse-leave="cellMouseLeave">
      <!--<el-table-column type="selection" width="55" />-->
      <el-table-column type="index" width="55" ></el-table-column>
      <el-table-column prop="name" label="名称" sortable>
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">  <!-- 判断修改还是添加 状态如何验证-->
            <el-row :gutter="20">
              <el-col :span="16">
                <el-input ref="newFolderName" v-model="scope.row.name"  size="mini"></el-input>
              </el-col>
              <el-col v-if="!rename" :span="6">
                <el-button type="primary" size="mini" icon="el-icon-check" plain @click.stop="newFolderOk(scope.row,scope.$index)"></el-button>
                <el-button type="danger" size="mini" icon="el-icon-close" plain @click.stop="newFolderCancel(scope.row)"></el-button>
              </el-col>
              <el-col v-else :span="6">
                <el-button type="primary" size="mini" icon="el-icon-check" plain @click.stop="renameOk(scope.row,scope.$index)"></el-button>
                <el-button type="danger" size="mini" icon="el-icon-close" plain @click.stop="renameCancel(scope.row)"></el-button>
              </el-col>
            </el-row>
          </template>
          <template v-else>
            <template v-if="scope.row.directory">
              <i class="el-icon-folder-opened"></i>{{ scope.row.name }}
            </template>
            <template v-if="scope.row.file">
              <i class="el-icon-document"></i>{{ scope.row.name }}
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="大小" sortable>
        <template slot-scope="scope">
          <template v-if="scope.row.directory">
            <i class="el-icon-minus"></i>
          </template>
          <template v-if="scope.row.file">
            <el-row :gutter="20">
              <el-col :span="6">
                {{ converUnit(scope.row.size) }}
              </el-col>
              <el-col :span="6" v-if="!scope.row.showProcess">
                <el-button type="primary" v-if="scope.row.showBtns" size="mini" icon="el-icon-download"  @click.stop="rowDowlond(scope.row)" circle plain></el-button>
                <el-button type="primary"  v-if="scope.row.showBtns" size="mini" icon="el-icon-more"  @click.stop="rowContextmenu(scope.row, scope.column, $event)" circle plain></el-button>
              </el-col>
              <el-col :span="6">
                <el-progress v-if="scope.row.showProcess" :percentage="scope.row.processValue"></el-progress>
              </el-col>
            </el-row>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="timestamp" label="修改日期" sortable>
        <template slot-scope="scope">
        {{parseTime(scope.row.timestamp)}}
        </template>
      </el-table-column>
    </el-table>
    <f-ftp-context-menu ref="contextmenu" v-if="contextmenuVisible" @foo="foo" @handleDowload="handleDowload" @handleRename="handleRename" @handleDelete="handleDelete" ></f-ftp-context-menu>
  </div>
</template>
<script>
  import FFtpContextMenu from '@/pages/ftp/components/f-ftpContextMenu'
  import {MessageUtils} from '@/utils/business.js'
  import { parseTime, converUnit } from '@/utils/index'
  import crudAPI from '@/api/ftp/ftp'
  import CRUD, {presenter, header, crud} from '@/components/f-crud/f-crud'
  import { rrOperation, crudOperation, udOperation } from '@/components/f-crud'
  export default {
    mixins: [presenter(), header(), crud()],
    components: {crudOperation, rrOperation, udOperation, FFtpContextMenu},
    cruds () {
      return CRUD({title: 'FTP', url: crudAPI.list, crudMethod: { ...crudAPI }, query: {}})
    },
    data () {
      return {
        permission: {
          add: ['admin', 'putong'],
          edit: ['admin', 'putong'],
          del: ['admin', 'putong']
        },
        suffixFolder: '',
        contextmenuVisible: false,
        tableRow: null,
        rename: false, // newFolder / rename
        hoverIndex: null,
        downloadSize: 0
      }
    },
    created () {
      // 需要显示的头部按钮
      this.crud.optShow = {
        add: false,
        edit: false,
        del: false,
        download: false
      }
    },
    methods: {
      parseTime,
      converUnit,
      [CRUD.HOOK.beforeResetQuery] (crud, form) { // 重置之前的操作
        this.suffixFolder = ''
      },
      tableRowClassName ({row, rowIndex}) { // 渲染行样式
        if (this.hoverIndex === rowIndex) {
          row.showBtns = true
        } else {
          row.showBtns = false
        }
        row.index = rowIndex
        if (this.tableRow && rowIndex === this.tableRow.index) {
          return 'row-content'
        }
        return ''
      },
      rowClick (row, column, event) { // 点击文件夹
        if (this.$refs.newFolderName) {
          this.$refs.newFolderName.select()
          return
        }
        if (row.directory) {
          this.suffixFolder += '/' + row.name
          this.crud.query.suffixFolder = this.suffixFolder
          this.crud.toQuery()
        }
      },
      cellMouseEnter (row, column, cell, event) { // 移入
       this.hoverIndex = row.index
      },
      cellMouseLeave (row, column, cell, event) { // 移出
        this.hoverIndex = null
      },
      goBack () { // 返回上一级
        if (this.suffixFolder.lastIndexOf('/') > -1) { // 出现最后一个字符/位置 截取到最后
          this.suffixFolder = this.suffixFolder.substr(0, this.suffixFolder.lastIndexOf('/'))
          this.crud.query.suffixFolder = this.suffixFolder
          this.crud.toQuery()
        }
      },
      goBackFirst () { // 返回顶层
        this.suffixFolder = ''
        this.crud.query.suffixFolder = this.suffixFolder
        this.crud.toQuery()
      },
      downloadList () {
        this.$notify({
          title: '自定义位置',
          duration: 0,
          message: '右下角弹出的消息',
          position: 'bottom-right'
        })
      },
      newFolder () { // 创建文件夹
        if (this.$refs.newFolderName) {
          this.$refs.newFolderName.select()
          return
        }
        this.changeTag = 'newFolder'
        const row = {id: '', 'isEdit': true, name: '新建文件夹', directory: true, file: false}
        this.crud.data.push(row)
        this.$nextTick(() => {
          this.$refs.newFolderName.select()
        })
      },
      newFolderOk (row, index) { // 创建文件夹 保存
        const params = {
          folderName: row.name,
          folderPath: this.suffixFolder
        }
        crudAPI.newFolder(params).then((res) => {
          if (res.status === 200) {
            row.isEdit = false
            row.name = res.data.name
            row.timestamp = res.data.timestamp
          }
        })
      },
      uploadFile (obj) { // 上传文件
        if (obj.file.size / 1024 / 1024 > 100) {
          new MessageUtils().WARNING('上传文件大小限制100MB以内!')
          return
        }
        let that = this
        let formData = new FormData()
        formData.append('file', obj.file)
        formData.append('folderPath', this.suffixFolder) // 上传文件的同时， 也可以上传其他数据
        crudAPI.updateFile(formData).then((res) => {
          if (res.status === 200) {
            that.crud.data.push(res.data)
          }
        })
      },
      newFolderCancel (row) { // 创建文件夹 取消
        row.isEdit = false
        this.crud.data.splice((this.crud.data.length - 1), 1)
      },
      renameOk (row, index) { // 重命名 保存
        const that = this
        if (that.rename === row.name) {
          row.isEdit = false
          that.rename = false
          return
        }
        const params = {
          srcName: that.rename,
          toName: row.name,
          folderPath: that.suffixFolder
        }
        crudAPI.rename(params).then((res) => {
          if (res.status === 200) {
            row.isEdit = false
            that.rename = false
          }
        })
      },
      renameCancel (row) { // 重命名 取消
        row.isEdit = false
        row.name = this.rename
        this.rename = false
      },
      rowDowlond (row) { // 下载
        this.tableRow = row
        this.handleDowload()
      },
      rowContextmenu (row, column, event) { // 表格行右键
        this.tableRow = row
        this.contextmenuVisible = true
        // 阻止右键默认行为
        event.preventDefault()
        this.$nextTick(() => {
          this.$refs.contextmenu.init(row, column, event)
        })
      },
      foo () {
        this.tableRow = null
        this.contextmenuVisible = false
        document.removeEventListener('click', this.foo)
      },
      handleRename () { // 重命名
        if (this.$refs.newFolderName) {
          this.$refs.newFolderName.select()
          return
        }
        this.tableRow.isEdit = true
        this.rename = this.tableRow.name
        setTimeout(() => {
          this.$refs.newFolderName.select()
        }, 0)
      },
      handleDelete () { // 删除
        const params = {
          name: this.tableRow.name,
          type: (this.tableRow.directory ? 'dir' : this.tableRow.file ? 'file' : ''),
          folderPath: this.suffixFolder
        }
        const obj = this.findRowIndexOfData(params.type, params.name)
        crudAPI.del(params).then((res) => {
          if (res.status === 200) {
            this.crud.data.splice(obj.index, 1)
          }
        })
      },
      handleDowload () { // 下载
        if (this.downloadSize > 0) {
          new MessageUtils().WARNING('每次只能下载一个文件!')
          return
        }
        this.downloadSize = 1
        let params = {
          name: this.tableRow.name,
          type: (this.tableRow.directory ? 'dir' : this.tableRow.file ? 'file' : ''),
          folderPath: this.suffixFolder
        }
        const obj = this.findRowIndexOfData(params.type, params.name)
        // 显示进度条
        let crudRowData = obj.row
        crudRowData.processValue = 0
        crudAPI.download(params).then((res) => { // 下载文件
        })
        let timeInterVal = setInterval(() => {
          let params = {
            name: crudRowData.name
          }
          crudAPI.findProcess(params).then((res) => {
            if (res.status === 200) {
              if (res.data != null) {
                crudRowData.showProcess = true
                crudRowData.processValue = res.data
                if (res.data === 100) {
                  clearInterval(timeInterVal)
                  setTimeout(() => {
                    crudRowData.showProcess = false
                    this.downloadSize = 0
                  }, 2000)
                }
              }
            } else {
              clearInterval(timeInterVal)
              crudRowData.showProcess = false
              this.downloadSize = 0
            }
          })
        }, 1000)
      },
      findRowIndexOfData (type, name) { // 获取表格中的索引
        const obj = {
          'index': null,
          'row': null
        }
        const data = this.crud.data
        for (let index in data) {
          if (data[index].directory && type === 'dir' && data[index].name === name) {
            obj.index = index
            obj.row = data[index]
            return obj
          }
          if (data[index].file && type === 'file' && data[index].name === name) {
            obj.index = index
            obj.row = data[index]
            return obj
          }
        }
      }
    }
  }
</script>
<style scoped>
  .el-icon-folder-opened{
    color: #FFD659;
  }
  .el-icon-document,.el-icon-folder-opened{
    font-size: 20px;
    padding-right: 10px;
  }

</style>
<style>
  .el-table .row-content{
    background: #F2F6FC;
  }
  .f-upload{
    display: inline-block;
    margin:0px 10px;
  }
  .el-table .el-progress{
    line-height: none !important;
  }
</style>
